from django.shortcuts import render
from django.views import View
from alipay import AliPay
from django.conf import settings
from django import http
import os
import logging

from orders.models import OrderInfo
from payment.models import Payment

# Create your views here.

# 创建日志生成器
logger = logging.getLogger('django')


class PaymentStatusView(View):
    def put(self, request):
        # 提取参数
        query_dict = request.GET
        com_dict = query_dict.dict()
        signature = query_dict.pop('sign')

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),
            debug=settings.ALIPAY_DEBUG,
            sign_type="RSA2"
        )

        success = alipay.verify(com_dict, signature)
        if success:
            trade_id = com_dict.get('trade_no')
            payment = Payment.objects.create(
                order_id=com_dict.get('out_trade_no'),
                trade_id=trade_id
            )
            payment.order.status = com_dict.get('status')
            # payment.order.status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
            payment.order.save()
            return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'trade_id': trade_id})

        return http.JsonResponse({'code': 400, 'errmsg': '支付失败'})


class PaymentView(View):
    def get(self, request, order_id):

        try:
            order = OrderInfo.objects.get(order_id=order_id,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400, 'errmsg': '订单号无效'})

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                              'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                'keys/alipay_public_key.pem'),
            debug=settings.ALIPAY_DEBUG,
            sign_type="RSA2"
        )

        # 生成登录支付宝链接
        order_string = alipay.api_alipay_trade_page_pay(
            subject='美多商城: %s' % order_id,
            out_trade_no=order_id,
            total_amount=float(order.total_amount),
            return_url=settings.ALIPAY_RETURN_URL
        )

        alipay_url = settings.ALIPAY_URL + '?' + order_string

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'alipay_url': alipay_url})




